#include "gamerenderer.h"
#include <QPainter>
#include <QDateTime>
#include <QDebug>
#include <QtMath>
#include <QRandomGenerator>

GameRenderer::GameRenderer(QWidget *parent)
    : QWidget(parent)
    , m_renderTimer(new QTimer(this))
    , m_fpsTimer(new QTimer(this))
    , m_lastFrameTime(0)
    , m_frameCount(0)
    , m_currentFPS(0)
    , m_cellSize(20)
    , m_gridSize(40, 30)
    , m_useCustomFrame(false)
    , m_frameNeedsUpdate(true)
    , m_gridCacheValid(false)
{
    // 设置基本属性
    setMinimumSize(800, 600);
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    setFocusPolicy(Qt::NoFocus); // 渲染器不需要焦点

    // 性能优化属性
    setAttribute(Qt::WA_OpaquePaintEvent, true);  // 减少背景清除
    setAttribute(Qt::WA_NoSystemBackground, true); // 禁用系统背景
    
    // 初始化渲染配置
    m_config.targetFPS = 60;
    m_config.enableInterpolation = true;
    m_config.enableEffects = true;
    m_config.enableVSync = true;
    m_config.animationSpeed = 1.0f;
    m_config.maxParticles = 100;
    
    // 初始化动画状态
    m_currentAnimation.lastUpdateTime = QDateTime::currentMSecsSinceEpoch();
    m_currentAnimation.snakeHeadRotation = 0.0f;
    m_currentAnimation.effectPhase = 0.0f;

    // 初始化预测状态（避免显示垃圾值）
    m_predictedState.score = 0;
    m_predictedState.isValid = false;
    
    // 设置60FPS渲染定时器
    m_renderTimer->setInterval(1000 / m_config.targetFPS);
    connect(m_renderTimer, &QTimer::timeout, this, &GameRenderer::onRenderTick);
    
    // 设置FPS统计定时器
    m_fpsTimer->setInterval(1000); // 每秒更新一次FPS
    connect(m_fpsTimer, &QTimer::timeout, this, &GameRenderer::onFPSTimer);
    
    // 初始化游戏区域
    int gameWidth = m_gridSize.width() * m_cellSize;
    int gameHeight = m_gridSize.height() * m_cellSize;
    m_gameArea = QRectF(0, 0, gameWidth, gameHeight);

    // 不再注入任何测试蛇，等待服务器首帧

    // 暂时禁用GameRenderer自己的FPS计时器，避免与RenderThread的FPS统计冲突
    m_renderTimer->start();
    // m_fpsTimer->start(); // 暂时禁用，使用RenderThread的FPS

    qDebug() << "GameRenderer: 高性能渲染器初始化完成";
    qDebug() << "  目标FPS:" << m_config.targetFPS;
    qDebug() << "  插值渲染:" << (m_config.enableInterpolation ? "启用" : "禁用");
    qDebug() << "  视觉特效:" << (m_config.enableEffects ? "启用" : "禁用");
}

void GameRenderer::setPredictedState(const ClientPrediction::PredictedState &predictedState)
{
    if (!predictedState.isValid) {
        qDebug() << "GameRenderer: 接收到无效的预测状态";
        return;
    }

    qDebug() << "GameRenderer: 设置预测状态 - 蛇长度:" << predictedState.snakeBody.size()
             << "方向:" << predictedState.direction << "分数:" << predictedState.score;

    m_predictedState = predictedState;
    
    // 更新目标动画状态
    m_targetAnimation.snakePositions.clear();
    for (const QPoint &segment : predictedState.snakeBody) {
        m_targetAnimation.snakePositions.append(QPointF(segment));
    }
    
    // 计算蛇头旋转角度
    if (predictedState.snakeBody.size() >= 2) {
        QPoint head = predictedState.snakeBody[0];
        QPoint neck = predictedState.snakeBody[1];
        QPoint direction = head - neck;
        
        if (direction.x() > 0) m_targetAnimation.snakeHeadRotation = 0;      // RIGHT
        else if (direction.x() < 0) m_targetAnimation.snakeHeadRotation = 180; // LEFT
        else if (direction.y() < 0) m_targetAnimation.snakeHeadRotation = 270; // UP
        else if (direction.y() > 0) m_targetAnimation.snakeHeadRotation = 90;  // DOWN
    }
    
    // 如果当前动画状态为空，立即设置（用于初始化）
    if (m_currentAnimation.snakePositions.isEmpty()) {
        m_currentAnimation = m_targetAnimation;
        qDebug() << "GameRenderer: 立即设置初始动画状态";
        qDebug() << "  设置后当前动画蛇位置数量:" << m_currentAnimation.snakePositions.size();
        update(); // 强制重绘
    } else {
        qDebug() << "GameRenderer: 当前动画状态不为空，数量:" << m_currentAnimation.snakePositions.size();
    }

    // 不需要立即重绘，让60FPS定时器处理
}

void GameRenderer::forceCurrentToTarget()
{
    qDebug() << "GameRenderer: 强制同步当前状态到目标状态";
    m_currentAnimation = m_targetAnimation;
    qDebug() << "  同步后当前动画蛇位置数量:" << m_currentAnimation.snakePositions.size();
    update(); // 强制重绘
}

void GameRenderer::setServerState(const QList<QPoint> &snakeBody, const QList<QPoint> &foods)
{
    qDebug() << "=== GameRenderer::setServerState ===";
    qDebug() << "收到服务器状态 - 蛇身长度:" << snakeBody.size() << "食物数量:" << foods.size();

    m_serverSnakeBody = snakeBody;
    m_serverFoods = foods;

    // 首次收到有效服务器状态时，清空测试蛇并切换到服务器状态
    static bool hasReceivedServerState = false;
    if (!hasReceivedServerState && (!snakeBody.isEmpty() || !foods.isEmpty())) {
        qDebug() << "首次收到服务器状态，清空测试蛇";
        hasReceivedServerState = true;

        // 清空测试蛇，使用服务器状态
        m_currentAnimation.snakePositions.clear();
        m_targetAnimation.snakePositions.clear();

        // 设置蛇的位置
        for (const QPoint &segment : snakeBody) {
            m_currentAnimation.snakePositions.append(QPointF(segment));
            m_targetAnimation.snakePositions.append(QPointF(segment));
        }
    } else if (hasReceivedServerState) {
        // 后续更新只修改目标状态，让插值动画处理
        m_targetAnimation.snakePositions.clear();
        for (const QPoint &segment : snakeBody) {
            m_targetAnimation.snakePositions.append(QPointF(segment));
        }
    }

    // 更新食物位置
    m_targetAnimation.foodPositions.clear();
    for (const QPoint &food : foods) {
        m_targetAnimation.foodPositions.append(QPointF(food));
    }

    qDebug() << "状态更新完成 - 当前蛇段数:" << m_currentAnimation.snakePositions.size()
             << "目标蛇段数:" << m_targetAnimation.snakePositions.size()
             << "食物数:" << m_targetAnimation.foodPositions.size();
    
    qDebug() << "GameRenderer: 服务器状态更新 - 蛇长度:" << snakeBody.size() 
             << "食物数量:" << foods.size();
}

void GameRenderer::setRenderConfig(const RenderConfig &config)
{
    m_config = config;
    
    // 更新渲染定时器频率
    m_renderTimer->setInterval(1000 / m_config.targetFPS);
    
    qDebug() << "GameRenderer: 渲染配置更新";
    qDebug() << "  目标FPS:" << m_config.targetFPS;
    qDebug() << "  插值渲染:" << (m_config.enableInterpolation ? "启用" : "禁用");
}

void GameRenderer::playEffect(const QString &effectType, const QPointF &position)
{
    if (!m_config.enableEffects) {
        return;
    }
    
    // 创建粒子特效
    for (int i = 0; i < 10; ++i) {
        Particle particle;
        particle.position = position;
        particle.velocity = QPointF(
            (QRandomGenerator::global()->bounded(200) - 100) / 100.0f,
            (QRandomGenerator::global()->bounded(200) - 100) / 100.0f
        );
        particle.life = 1.0f;
        particle.maxLife = 1.0f;
        particle.color = QColor::fromHsv(QRandomGenerator::global()->bounded(360), 255, 255);
        particle.size = 2.0f + QRandomGenerator::global()->bounded(3);
        
        m_particles.append(particle);
    }
    
    // 限制粒子数量
    while (m_particles.size() > m_config.maxParticles) {
        m_particles.removeFirst();
    }
    
    qDebug() << "GameRenderer: 播放特效:" << effectType << "位置:" << position;
}

void GameRenderer::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)

    QPainter painter(this);
    // 绘制位图不需要抗锯齿，关闭以提升性能
    painter.setRenderHint(QPainter::Antialiasing, false);

    // 记录渲染开始时间
    qint64 renderStartTime = QDateTime::currentMSecsSinceEpoch();

    // 强制优先显示自定义帧（统一渲染管线输出）
    if (m_useCustomFrame && !m_customFrame.isNull()) {
        static int debugCount = 0;
        if (++debugCount % 60 == 1) { // 每秒输出一次
            qDebug() << "=== GameRenderer 自定义帧显示调试 ===";
            qDebug() << "  自定义帧尺寸:" << m_customFrame.size();
            qDebug() << "  GameRenderer尺寸:" << size();
            qDebug() << "  游戏区域:" << m_gameArea;
        }

        // 检查是否需要重新缩放
        // 不缩放到整个窗口，而是缩放到游戏区域
        QSize targetSize = m_gameArea.size().toSize();

        // 如果源帧尺寸与目标尺寸一致，则直接绘制，避免每帧缩放带来的卡顿
        if (m_customFrame.size() == targetSize) {
            m_lastSize = size();
            m_frameNeedsUpdate = false;

            // 在游戏区域内居中显示原始帧
            int x = m_gameArea.x() + (m_gameArea.width() - targetSize.width()) / 2;
            int y = m_gameArea.y() + (m_gameArea.height() - targetSize.height()) / 2;
            painter.drawPixmap(x, y, m_customFrame);
        } else {
            // 仅当窗口大小、源帧尺寸或标记变化时才重新生成缩放帧
            if (m_frameNeedsUpdate || m_lastSize != size() || m_lastSourceFrameSize != m_customFrame.size()) {
                m_scaledFrame = m_customFrame.scaled(targetSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
                m_lastSize = size();
                m_lastSourceFrameSize = m_customFrame.size();
                m_frameNeedsUpdate = false;

                if (debugCount % 60 == 1) {
                    qDebug() << "  目标尺寸:" << targetSize;
                    qDebug() << "  缩放后尺寸:" << m_scaledFrame.size();
                }
            }

            // 在游戏区域内居中显示缩放帧
            int x = m_gameArea.x() + (m_gameArea.width() - m_scaledFrame.width()) / 2;
            int y = m_gameArea.y() + (m_gameArea.height() - m_scaledFrame.height()) / 2;
            painter.drawPixmap(x, y, m_scaledFrame);
        }


    } else {
        // 统一渲染管线未就绪时显示等待界面，不使用原生渲染
        static int debugCount = 0;
        if (++debugCount % 60 == 1) { // 每秒输出一次
            qDebug() << "=== GameRenderer 等待统一渲染管线 ===";
            qDebug() << "  游戏区域:" << m_gameArea;
            qDebug() << "  等待自定义帧...";
        }

        painter.save();
        painter.setClipRect(m_gameArea);
        painter.translate(m_gameArea.topLeft());

        // 显示等待界面而不是原生渲染
        renderWaitingScreen(painter);

        painter.restore();
    }

    // 计算渲染时间
    qint64 renderTime = QDateTime::currentMSecsSinceEpoch() - renderStartTime;
    
    // 更新帧计数
    m_frameCount++;
    
    // 发送性能统计（每60帧发送一次）
    if (m_frameCount % 60 == 0) {
        emit renderPerformance(renderTime, m_predictedState.snakeBody.size() * 4); // 简单的三角形计数
    }
}

void GameRenderer::renderWaitingScreen(QPainter &painter)
{
    // 使用网格缓存显示等待界面
    if (!m_gridCacheValid || m_gridCache.isNull()) {
        // 重新生成网格缓存
        QSize gameSize(m_gameArea.width(), m_gameArea.height());
        m_gridCache = QPixmap(gameSize);
        m_gridCache.fill(QColor(26, 26, 46));  // 深蓝背景

        QPainter gridPainter(&m_gridCache);
        gridPainter.setPen(QPen(QColor(51, 51, 51), 1));

        int cellSize = 20;
        int cols = gameSize.width() / cellSize;
        int rows = gameSize.height() / cellSize;

        // 绘制网格线
        for (int x = 0; x <= cols; ++x) {
            gridPainter.drawLine(x * cellSize, 0, x * cellSize, gameSize.height());
        }
        for (int y = 0; y <= rows; ++y) {
            gridPainter.drawLine(0, y * cellSize, gameSize.width(), y * cellSize);
        }

        m_gridCacheValid = true;
    }

    // 绘制缓存的网格
    painter.drawPixmap(0, 0, m_gridCache);

    // 绘制等待文本和动画
    painter.setPen(Qt::white);
    painter.setFont(QFont("Arial", 16, QFont::Bold));

    QString waitingText = "正在同步游戏数据...";
    QFontMetrics fm(painter.font());
    QRect textRect = fm.boundingRect(waitingText);

    int textX = (m_gameArea.width() - textRect.width()) / 2;
    int textY = (m_gameArea.height() - textRect.height()) / 2;

    painter.drawText(textX, textY, waitingText);

    // 简单的加载动画（旋转圆圈）
    static int rotationAngle = 0;
    rotationAngle = (rotationAngle + 10) % 360;

    painter.save();
    painter.translate(textX + textRect.width() + 20, textY + textRect.height() / 2);
    painter.rotate(rotationAngle);
    painter.setPen(QPen(Qt::cyan, 2));
    painter.drawArc(-10, -10, 20, 20, 0, 270 * 16); // 3/4 圆圈
    painter.restore();
}

void GameRenderer::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);

    // 重新计算游戏区域
    int gameWidth = m_gridSize.width() * m_cellSize;
    int gameHeight = m_gridSize.height() * m_cellSize;

    int x = (width() - gameWidth) / 2;
    int y = (height() - gameHeight) / 2;

    m_gameArea = QRectF(x, y, gameWidth, gameHeight);

    // 窗口大小改变时，网格缓存失效
    m_gridCacheValid = false;

    qDebug() << "GameRenderer: 窗口大小变化";
    qDebug() << "  渲染器大小:" << size();
    qDebug() << "  游戏区域:" << m_gameArea;
    qDebug() << "  网格大小:" << m_gridSize;
    qDebug() << "  单元格大小:" << m_cellSize;
}

void GameRenderer::onRenderTick()
{
    // 使用统一渲染管线时，不在本地执行插值/动画与额外重绘，避免重复刷新造成抖动
    if (m_useCustomFrame) {
        return;
    }

    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    float deltaTime = (currentTime - m_currentAnimation.lastUpdateTime) / 1000.0f;

    // 更新插值和动画
    if (m_config.enableInterpolation) {
        updateInterpolation(deltaTime);
    }

    updateAnimations(deltaTime);

    m_currentAnimation.lastUpdateTime = currentTime;

    // 触发重绘
    update();
}

void GameRenderer::onFPSTimer()
{
    // 计算FPS
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    if (m_lastFrameTime > 0) {
        float timeDiff = (currentTime - m_lastFrameTime) / 1000.0f;
        m_currentFPS = qRound(m_frameCount / timeDiff);
        
        // 计算平均帧时间
        float averageFrameTime = timeDiff / m_frameCount * 1000.0f;
        
        emit frameRateUpdated(m_currentFPS, averageFrameTime);
    }
    
    m_lastFrameTime = currentTime;
    m_frameCount = 0;
}

void GameRenderer::updateInterpolation(float deltaTime)
{
    if (m_targetAnimation.snakePositions.isEmpty()) {
        return;
    }

    // 使用缓动函数的插值因子
    float baseLerpFactor = qMin(deltaTime * 8.0f * m_config.animationSpeed, 1.0f);
    float smoothLerpFactor = 1.0f - qPow(1.0f - baseLerpFactor, 3.0f); // 三次缓动

    // 高级蛇身插值 - 每个段都有轻微的延迟
    if (m_currentAnimation.snakePositions.size() != m_targetAnimation.snakePositions.size()) {
        // 如果蛇长度改变，需要特殊处理
        if (m_targetAnimation.snakePositions.size() > m_currentAnimation.snakePositions.size()) {
            // 蛇变长了，添加新段
            while (m_currentAnimation.snakePositions.size() < m_targetAnimation.snakePositions.size()) {
                QPointF lastPos = m_currentAnimation.snakePositions.isEmpty() ?
                    QPointF(0, 0) : m_currentAnimation.snakePositions.last();
                m_currentAnimation.snakePositions.append(lastPos);
            }
        } else if (m_targetAnimation.snakePositions.size() < m_currentAnimation.snakePositions.size()) {
            // 蛇变短了，移除尾部段
            while (m_currentAnimation.snakePositions.size() > m_targetAnimation.snakePositions.size()) {
                m_currentAnimation.snakePositions.removeLast();
            }
        }
    }

    // 简化插值，减少蛇身体脱节
    for (int i = 0; i < m_currentAnimation.snakePositions.size(); ++i) {
        // 对于蛇身，使用更快的插值以减少脱节
        float segmentLerpFactor = (i == 0) ? smoothLerpFactor : smoothLerpFactor * 1.5f;
        segmentLerpFactor = qMin(segmentLerpFactor, 1.0f);

        m_currentAnimation.snakePositions[i] = lerp(
            m_currentAnimation.snakePositions[i],
            m_targetAnimation.snakePositions[i],
            segmentLerpFactor
        );
    }

    // 平滑蛇头旋转
    float rotationDiff = m_targetAnimation.snakeHeadRotation - m_currentAnimation.snakeHeadRotation;
    if (rotationDiff > 180) rotationDiff -= 360;
    if (rotationDiff < -180) rotationDiff += 360;

    m_currentAnimation.snakeHeadRotation += rotationDiff * smoothLerpFactor;

    // 食物的弹性插值
    if (m_currentAnimation.foodPositions.size() != m_targetAnimation.foodPositions.size()) {
        m_currentAnimation.foodPositions = m_targetAnimation.foodPositions;
    } else {
        for (int i = 0; i < m_currentAnimation.foodPositions.size(); ++i) {
            // 食物使用弹性缓动
            float elasticFactor = 1.0f - qPow(1.0f - baseLerpFactor, 2.0f);
            m_currentAnimation.foodPositions[i] = lerp(
                m_currentAnimation.foodPositions[i],
                m_targetAnimation.foodPositions[i],
                elasticFactor
            );
        }
    }
}

void GameRenderer::renderGame(QPainter &painter)
{
    static int debugCount = 0;
    if (++debugCount % 60 == 1) { // 每秒输出一次
        qDebug() << "GameRenderer: 渲染游戏帧";
        qDebug() << "  窗口大小:" << size();
        qDebug() << "  游戏区域:" << m_gameArea;
        qDebug() << "  蛇段数:" << m_currentAnimation.snakePositions.size();
        qDebug() << "  食物数:" << m_currentAnimation.foodPositions.size();
    }

    // 清除背景
    painter.fillRect(rect(), QColor(20, 20, 30));

    // 使用网格缓存优化
    if (!m_gridCacheValid || m_gridCache.isNull()) {
        // 重新生成网格缓存
        QSize gameSize(m_gameArea.width(), m_gameArea.height());
        m_gridCache = QPixmap(gameSize);
        m_gridCache.fill(QColor(40, 40, 50));  // 游戏区域背景色

        QPainter gridPainter(&m_gridCache);
        gridPainter.setPen(QPen(QColor(60, 60, 70), 1));

        // 绘制网格线
        for (int x = 0; x <= m_gridSize.width(); ++x) {
            float xPos = x * m_cellSize;
            gridPainter.drawLine(xPos, 0, xPos, gameSize.height());
        }
        for (int y = 0; y <= m_gridSize.height(); ++y) {
            float yPos = y * m_cellSize;
            gridPainter.drawLine(0, yPos, gameSize.width(), yPos);
        }

        m_gridCacheValid = true;
        if (debugCount % 60 == 1) {
            qDebug() << "  网格缓存已重新生成，大小:" << gameSize;
        }
    }

    // 直接绘制缓存的网格
    painter.drawPixmap(m_gameArea.topLeft(), m_gridCache);
    
    // 渲染游戏对象
    renderFood(painter);
    renderSnake(painter);
    
    if (m_config.enableEffects) {
        renderEffects(painter);
    }
    
    renderUI(painter);
}

void GameRenderer::renderSnake(QPainter &painter)
{
    static int debugCount = 0;
    if (++debugCount % 30 == 1) { // 每半秒输出一次
        qDebug() << "GameRenderer::renderSnake - 调试信息:";
        qDebug() << "  当前动画蛇位置数量:" << m_currentAnimation.snakePositions.size();
        qDebug() << "  目标动画蛇位置数量:" << m_targetAnimation.snakePositions.size();
        qDebug() << "  预测状态有效:" << m_predictedState.isValid;
        qDebug() << "  预测状态蛇长度:" << m_predictedState.snakeBody.size();
        if (!m_currentAnimation.snakePositions.isEmpty()) {
            qDebug() << "  蛇头位置:" << m_currentAnimation.snakePositions.first();
        }
        if (!m_predictedState.snakeBody.isEmpty()) {
            qDebug() << "  预测蛇头位置:" << m_predictedState.snakeBody.first();
        }
    }

    if (m_currentAnimation.snakePositions.isEmpty()) {
        qDebug() << "GameRenderer: 蛇位置为空，无法渲染！";
        return;
    }

    // 渲染蛇身 - 渐变效果
    for (int i = 1; i < m_currentAnimation.snakePositions.size(); ++i) {
        QPointF pos = m_currentAnimation.snakePositions[i];
        QRectF segmentRect(
            m_gameArea.x() + pos.x() * m_cellSize + 2,
            m_gameArea.y() + pos.y() * m_cellSize + 2,
            m_cellSize - 4,
            m_cellSize - 4
        );

        // 根据段的位置计算颜色渐变
        float intensity = 1.0f - (float(i) / m_currentAnimation.snakePositions.size()) * 0.5f;
        QColor segmentColor = QColor::fromHsv(120, 255, int(200 * intensity)); // 绿色渐变

        painter.setPen(QPen(segmentColor.darker(), 2));
        painter.setBrush(QBrush(segmentColor));
        painter.drawRoundedRect(segmentRect, 4, 4);

        // 添加高光效果
        if (m_config.enableEffects) {
            QColor highlightColor = segmentColor.lighter(150);
            highlightColor.setAlpha(100);
            painter.setBrush(QBrush(highlightColor));
            QRectF highlightRect = segmentRect.adjusted(2, 2, -2, -2);
            painter.drawRoundedRect(highlightRect, 2, 2);
        }
    }

    // 渲染蛇头 - 特殊效果
    if (!m_currentAnimation.snakePositions.isEmpty()) {
        QPointF headPos = m_currentAnimation.snakePositions[0];
        QRectF headRect(
            m_gameArea.x() + headPos.x() * m_cellSize + 1,
            m_gameArea.y() + headPos.y() * m_cellSize + 1,
            m_cellSize - 2,
            m_cellSize - 2
        );

        // 蛇头发光效果
        if (m_config.enableEffects) {
            painter.setPen(Qt::NoPen);
            QRadialGradient glowGradient(headRect.center(), m_cellSize * 0.8f);
            glowGradient.setColorAt(0, QColor(0, 255, 0, 150));
            glowGradient.setColorAt(1, QColor(0, 255, 0, 0));
            painter.setBrush(QBrush(glowGradient));
            painter.drawEllipse(headRect.adjusted(-4, -4, 4, 4));
        }

        // 蛇头主体
        QRadialGradient headGradient(headRect.center(), m_cellSize * 0.4f);
        headGradient.setColorAt(0, QColor(100, 255, 100));
        headGradient.setColorAt(1, QColor(0, 200, 0));
        painter.setBrush(QBrush(headGradient));
        painter.setPen(QPen(Qt::darkGreen, 2));
        painter.drawEllipse(headRect);

        // 绘制眼睛 - 带动画
        painter.setBrush(QBrush(Qt::black));
        float eyeSize = m_cellSize * 0.12f;
        float blinkPhase = qSin(m_currentAnimation.effectPhase * 10.0f);
        float eyeHeight = eyeSize * (0.8f + 0.2f * blinkPhase);

        QPointF eyeOffset(m_cellSize * 0.25f, -m_cellSize * 0.15f);
        painter.drawEllipse(headRect.center() - eyeOffset, eyeSize, eyeHeight);
        painter.drawEllipse(headRect.center() + QPointF(eyeOffset.x(), eyeOffset.y()), eyeSize, eyeHeight);

        // 眼睛高光
        painter.setBrush(QBrush(Qt::white));
        float highlightSize = eyeSize * 0.4f;
        painter.drawEllipse(headRect.center() - eyeOffset + QPointF(eyeSize*0.2f, -eyeSize*0.2f),
                          highlightSize, highlightSize);
        painter.drawEllipse(headRect.center() + QPointF(eyeOffset.x(), eyeOffset.y()) + QPointF(eyeSize*0.2f, -eyeSize*0.2f),
                          highlightSize, highlightSize);
    }
}

void GameRenderer::renderFood(QPainter &painter)
{
    painter.setPen(QPen(Qt::darkRed, 2));
    painter.setBrush(QBrush(QColor(255, 100, 100)));
    
    for (const QPointF &foodPos : m_currentAnimation.foodPositions) {
        QRectF foodRect(
            m_gameArea.x() + foodPos.x() * m_cellSize + 3,
            m_gameArea.y() + foodPos.y() * m_cellSize + 3,
            m_cellSize - 6,
            m_cellSize - 6
        );
        painter.drawEllipse(foodRect);
    }
}

void GameRenderer::renderEffects(QPainter &painter)
{
    // 渲染粒子特效
    for (const Particle &particle : m_particles) {
        if (particle.life <= 0) continue;
        
        QColor color = particle.color;
        color.setAlphaF(particle.life / particle.maxLife);
        painter.setBrush(QBrush(color));
        painter.setPen(Qt::NoPen);
        
        QPointF screenPos(
            m_gameArea.x() + particle.position.x() * m_cellSize,
            m_gameArea.y() + particle.position.y() * m_cellSize
        );
        
        painter.drawEllipse(screenPos, particle.size, particle.size);
    }
}

void GameRenderer::renderUI(QPainter &painter)
{
    // 不再渲染FPS信息（由RenderThread统一管理）
    painter.setPen(Qt::white);
    painter.setFont(QFont("Arial", 12));
    // painter.drawText(10, 20, QString("FPS: %1").arg(m_currentFPS)); // 禁用

    // 渲染分数
    if (m_predictedState.isValid) {
        painter.drawText(10, 40, QString("Score: %1").arg(m_predictedState.score));
        painter.drawText(10, 60, QString("Length: %1").arg(m_predictedState.snakeBody.size()));
    } else {
        painter.drawText(10, 40, QString("Score: —"));
        painter.drawText(10, 60, QString("Length: —"));
    }
}

void GameRenderer::updateAnimations(float deltaTime)
{
    // 更新特效相位
    m_currentAnimation.effectPhase += deltaTime * m_config.animationSpeed;
    if (m_currentAnimation.effectPhase > 1.0f) {
        m_currentAnimation.effectPhase = 0.0f;
    }
    
    // 更新粒子
    for (auto it = m_particles.begin(); it != m_particles.end();) {
        it->life -= deltaTime;
        it->position += it->velocity * deltaTime;
        
        if (it->life <= 0) {
            it = m_particles.erase(it);
        } else {
            ++it;
        }
    }
}

QPointF GameRenderer::lerp(const QPointF &from, const QPointF &to, float factor)
{
    return from + (to - from) * factor;
}

void GameRenderer::setCustomFrame(const QPixmap &frame)
{
    // 首次收到统一管线自定义帧时，停止本地渲染定时器，避免重复驱动
    if (m_useCustomFrame == false && m_renderTimer && m_renderTimer->isActive()) {
        m_renderTimer->stop();
        qDebug() << "GameRenderer: 停止本地渲染定时器（使用统一渲染管线）";
    }

    // 仅当帧尺寸变化时，才需要重新计算缩放帧
    bool sizeChanged = (m_customFrame.size() != frame.size());
    m_customFrame = frame;
    m_useCustomFrame = true;
    if (sizeChanged) {
        m_frameNeedsUpdate = true; // 仅在尺寸变化时触发重新缩放
    }

    // 触发重绘
    update();
}
